package cn.zhz.customview.view.explosion;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AnticipateOvershootInterpolator;
import android.view.animation.DecelerateInterpolator;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;

import androidx.annotation.Nullable;
import cn.zhz.customview.Utils;

/**
 * @author: zhuanghz
 * @createdTime: 2019/6/5 14:14
 * @desc:
 */
public class ExplosionField extends View {


    private View view;
    private Bitmap bitmap;
    private Rect rect;
    private Particle[][] mParticles;
    private Paint mPaint;
    private ValueAnimator animator;
    private int[] mExpandInset = new int[2];


    public ExplosionField(Context context) {
        this(context, null);
    }

    public ExplosionField(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, 0);
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        setClickable(true);
        attachToActivity((Activity) getContext());
        mPaint = new Paint();
        animator = new ValueAnimator();
        animator.setDuration(1000);
//        animator.setInterpolator(new DecelerateInterpolator());
        animator.setFloatValues(0.0f, 1.0f);
        Arrays.fill(mExpandInset, Utils.dp2Px(32));
    }


    /**
     * 绘制View的快照
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawParticles(canvas);
        invalidate();
        onDetachedFromWindow();
    }

    private ViewGroup rootView;

    /**
     * 加载到当前屏幕上
     */
    public void attachToActivity(Activity activity) {
         rootView = activity.findViewById(Window.ID_ANDROID_CONTENT);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        rootView.addView(this, lp);
    }

    /**
     * 移除该view
     * */
    public void detachedOnActivity(){
        if(rootView!=null){
            rootView.removeView(this);
        }
    }



    /**
     * 开始执行爆炸效果
     * */
    public void startExplode(View view){
        this.view = view;
        Rect rect = new Rect();
        view.getGlobalVisibleRect(rect);
        int[] location = new int[2];
        getLocationOnScreen(location);
        rect.offset(-location[0], -location[1]);
        bitmap = createBitmap(view);
        mParticles=  createParticles(bitmap,rect);
        startAnim();
    }



    /**
     * 执行爆炸动画
     */
    public void startAnim() {
        animator.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationStart(Animator animation) {
                view.animate().alpha(0f).setDuration(150).start();
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                view.animate().alpha(1f).setDuration(150).start();
                detachedOnActivity();


            }
        });
        animator.start();
    }


    /**
     * 获取控件快照
     */
    private Bitmap createBitmap(View view) {
        //方法一，使用view的drawingCache
//        view.setDrawingCacheEnabled(true);
//        Bitmap bitmap= view.getDrawingCache();

        //方法二：使用绘制出来的进行操作
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        WeakReference<Bitmap> weakReference = new WeakReference<>(bitmap);
        if (weakReference.get() != null && !weakReference.get().isRecycled()) {
            Canvas canvas = new Canvas();
            canvas.setBitmap(weakReference.get());
            view.draw(canvas);
            canvas.setBitmap(null);
        }
        return weakReference.get();
    }

    /**
     * 生成粒子列表
     */
    private Particle[][] createParticles(Bitmap bitmap, Rect bound) {
        int w = bound.width();
        int h = bound.height();
        int wCount = w / Particle.PART_WH;//横向个数
        int hCount = h / Particle.PART_WH;//纵向个数
        int bitmap_part_w = bitmap.getWidth() / wCount;
        int bitmap_part_h = bitmap.getHeight() / hCount;
        Particle[][] particles = new Particle[wCount][hCount];
        for (int row = 0; row < wCount; row++) {
            for (int column = 0; column < hCount; column++) {
                int color = bitmap.getPixel(column * bitmap_part_w, row * bitmap_part_h);
                Point point = new Point(column, row);
                particles[row][column] = Particle.createParticle(color, bound, point);
            }
        }
        return particles;
    }

    /**
     * 绘制粒子
     */
    private void drawParticles(Canvas canvas) {
        if (mParticles == null) {
            return;
        }

        for (Particle[] particles : mParticles) {
            for (Particle p : particles) {
                p.dispersal((Float) animator.getAnimatedValue());
                mPaint.setColor(p.color);
                mPaint.setAlpha((int) (Color.alpha(p.color) * p.alpha));
                canvas.drawCircle(p.cx, p.cy, p.radius, mPaint);
            }
        }
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        release();

    }

    /**
     * 资源释放
     */
    public void release() {

    }

    /**
     * 密度
     */
    public static final float DENSITY = Resources.getSystem().getDisplayMetrics().density;

    public int dp2px(int dp) {
        return Math.round(dp * DENSITY);
    }


}
